package com.base.core.type;

import java.sql.Timestamp;
import java.util.Date;

import com.base.core.error.EnumWithText;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JsonUtils {
    private static ObjectMapper mapper = new ObjectMapper();

    private static ObjectMapper reader;

    private static ObjectMapper writer;

    public static ObjectMapper mapper() {
        return mapper;
    }

    public static ObjectMapper reader() {
        if (reader == null) {
            reader = new ObjectMapper();
            //reader.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
            SimpleModule module = new SimpleModule();
            module.addDeserializer(String.class, new SpecialStringDerializer());
            module.addDeserializer(Date.class, new SpecialDateDerializer());
            module.addDeserializer(Timestamp.class, new SpecialTimestampDerializer());
            reader.registerModule(module);
        }
        return reader;
    }

    public static ObjectMapper writer() {
        if (writer == null) {
            writer = new ObjectMapper();
            //writer.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            SimpleModule module = new SimpleModule();
            module.addSerializer(String.class, new SpecialStringSerializer());
            module.addSerializer(Timestamp.class, new SpecialTimestampSerializer());
            writer.registerModule(module);
        }
        return writer;
    }

    public static ObjectNode enumToObject(Class<?> fieldType) {
        ObjectNode on = mapper.createObjectNode();
        for (Object o : fieldType.getEnumConstants()) {
            EnumWithText e = (EnumWithText) o;
            on.put(e.toString(), e.text());
        }
        return on;
    }
}
